/**
 * 登录界面
 */
import React, {Component} from 'react';
import {View, StyleSheet, Image, Text, Alert,AsyncStorage, TextInput} from  'react-native';
import {Kaede} from 'react-native-textinput-effects';
import {CountDownText} from 'react-native-sk-countdown';
import Mock from 'mockjs';
import Button from 'react-native-button'
import Main from './Main/Main';
import { NavigationActions } from 'react-navigation'
export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            codeSent: false,
            code: '',
            loading: false,
            countingDown:false
        };

        this.onLogin = this.onLogin.bind(this);
        this._sendCode = this._sendCode.bind(this);
        this._showCode = this._showCode.bind(this);
        this._countDown = this._countDown.bind(this)

    }


    onLogin() {
        let that=this;
        fetch(that.props.api_url)
            .then((response) => response.json())
            .then((responseData) => {
                let data =Mock.mock(responseData);
                if (data.success) {
                    let userData=data.data[0];
                    let user=JSON.stringify(userData);
                    AsyncStorage.setItem('user',user)
                        .then(()=>{
                            // const {navigator} = that.props;
                            // if (navigator) {
                            //     navigator.push({
                            //         name: 'Main',
                            //         component: Main,
                            //     })
                            // }
                            const resetAction=NavigationActions.reset({index:0,actions:[NavigationActions.navigate({routeName:'Main'})]});
                            this.props.navigation.dispatch(resetAction)
                        })
                }

            })
            .catch((error) => {

            })

    }

    render() {
        return (
            <View style={styles.contain}>
                <View style={styles.loginStyle}>
                    <Text style={styles.titleStyle}>快速登录</Text>
                    <TextInput
                        placeholder="输入手机号"
                        autoCapitalize={"none"}
                        keyboardType="number-pad"
                        underlineColorAndroid="transparent"
                        style={styles.inputField1}
                        onChangeText={(text)=>{
                          this.setState({
                              phone:text
                          })
                      }}/>
                    {
                        this.state.codeSent ?
                            <View style={styles.codeBox}>
                                <TextInput
                                    placeholder="输入验证码"
                                    autoCapitalize={"none"}
                                    keyboardType="number-pad"
                                    blurOnSubmit={true}
                                    onFocus={()=>{

                                        }
                                    }
                                    underlineColorAndroid="transparent"
                                    style={styles.inputField}
                                    onChangeText={(text)=>{
                                        this.setState({
                                        code:text
                                    })
                      }}/>
                                {
                                    this.state.countingDown?
                                        <Button style={styles.countBtn}
                                                onPress={this._sendCode}>获取验证码</Button>
                                        :
                                        <CountDownText
                                            style={styles.countBtn}
                                            onPress={this._sendCode}
                                            countType='seconds' // 计时类型：seconds / date
                                            auto={true} // 自动开始
                                            afterEnd={this._countDown} // 结束回调
                                            timeLeft={60} // 正向计时 时间起点为0秒
                                            step={-1} // 计时步长，以秒为单位，正数则为正计时，负数为倒计时
                                            startText='获取验证码' // 开始的文本
                                            endText='获取验证码' // 结束的文本
                                            intervalText={(sec) => sec + '秒重新获取'} // 定时的文本回调
                                        />
                                }
                            </View>
                            : null
                    }
                    {
                        this.state.codeSent ?
                            <Button style={styles.btn} onPress={this.onLogin}>登录</Button>
                            :
                            <Button style={styles.btn} onPress={this._sendCode}>获取验证码</Button>
                    }
                </View>
            </View>
        );
    }
    _countDown(){
        this.setState({
            countingDown: true
        })
    }
    _sendCode() {
        let phone = this.state.phone;
        if (!phone) {
            Alert.alert("手机不能为空");
            return;
        }
        this._showCode()
    }

    _showCode() {
        this.setState({
            codeSent: true,
            countingDown: false
        })
    }
}
Login.propTypes = {
    api_url: React.PropTypes.string
};
Login.defaultProps = {
    api_url: 'http://rapapi.org/mockjs/18259/api/u/verify?phonenum=13132676138&verifycode=7767'
};
const styles = StyleSheet.create({
    contain: {
        flex: 1,
        backgroundColor: '#f9f9f9'
    },
    loginStyle: {
        marginTop: 30,
        padding: 10
    },
    titleStyle: {
        color: '#333',
        fontSize: 20,
        textAlign: 'center',
        marginBottom: 30,

    },
    btn: {
        marginTop: 10,
        padding:10,
        backgroundColor:'transparent',
        borderColor:'#ee735c',
        borderWidth:1,
        borderRadius:4,
        color:'#ee735c'
    },
    inputField: {
        flex:1,
        height: 40,
        padding: 5,
        color: '#666',
        fontSize: 16,
        backgroundColor: '#fff',
        borderRadius: 4
    },
    inputField1: {
        // flex:1,
        height: 40,
        padding: 5,
        color: '#666',
        fontSize: 16,
        backgroundColor: '#fff',
        borderRadius: 4
    },
    codeBox: {
        marginTop: 10,
        flexDirection:'row',
        justifyContent:'space-between'
    },
    countBtn:{
        width:120,
        height:40,
        padding:10,
        marginLeft:8,
        backgroundColor:'#ee735c',
        borderColor:'#ee735c',
        textAlign:'center',
        fontWeight:'600',
        fontSize:16,
        borderRadius:4,
        color:'white'
    }
});
